﻿using Autofac;
using Autofac.Integration.Mvc;
using Bmz.Studio.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace Bmz.Studio.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var builder = new ContainerBuilder();

            var typeFinder = new AppDomainTypeFinder();
            var drTypes = typeFinder.FindClassesOfType<IDependencyRegistrar>();
            var drInstances = new List<IDependencyRegistrar>();
            foreach (var item in drTypes)
            {
                drInstances.Add((IDependencyRegistrar)Activator.CreateInstance(item));
            }
            drInstances = drInstances.OrderBy(p => p.Order).ToList();
            foreach (var item in drInstances)
            {
                item.Register(builder, typeFinder);
            };
            // Register dependencies in controllers
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            var container = builder.Build();

            //set dependency resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}
